<!-- 备注档案模态窗口 -->
<div class="modal fade" id="profileModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">备注档案(测试)</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="profileForm" enctype="multipart/form-data">
                    <input type="hidden" name="subjectId" id="profile-subject-id">
                    <input type="hidden" name="trialId" id="profile-trial-id">
                    <input type="hidden" name="userId" id="profile-user-id">
                    <input type="hidden" name="attachmentUrls" id="profile-attachment-urls">

                    <div class="mb-3">
                        <label class="form-label">备注内容</label>
                        <textarea class="form-control" name="content" rows="4" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">保密级别</label>
                        <select class="form-select" name="secretLevel">
                            <option value="Unclassified">普通档案</option>
                            <option value="Confidential" selected>内部档案（默认）</option>
                            <option value="Secret">机密档案</option>
                            <option value="TopSecret">绝密档案</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">附件截图</label>
                        <div class="input-group mb-3">
                            <input type="file" class="form-control" id="profile-file-upload" accept="image/*" multiple>
                            <button class="btn btn-outline-secondary" type="button" id="upload-btn">上传</button>
                        </div>
                        <div class="form-text">支持多个JPG、PNG格式的图片</div>
                        <div id="upload-preview" class="mt-2 d-flex flex-wrap gap-2"></div>
                    </div>
                </form>

                <div id="profile-history" class="mt-4">
                    <h6>历史备注</h6>
                    <div id="profile-history-content">
                        <!-- 历史备注将在这里显示 -->
                        <div class="d-flex justify-content-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="submitProfile()">保存备注</button>
            </div>
        </div>
    </div>
</div>

<!-- 备注档案功能相关的JS脚本 -->
<script>
    // 显示备注档案模态框
    function showProfileModal(subjectId, trialId, userId) {
        document.getElementById('profile-subject-id').value = subjectId;
        document.getElementById('profile-trial-id').value = trialId;
        document.getElementById('profile-user-id').value = userId;
        document.getElementById('profile-attachment-urls').value = '';

        // 清空表单和预览
        document.getElementById('profileForm').reset();
        document.getElementById('upload-preview').innerHTML = '';

        // 加载历史备注
        loadProfileHistory(userId, subjectId, trialId);

        new bootstrap.Modal(document.getElementById('profileModal')).show();
    }

    // 加载历史备注
    async function loadProfileHistory(userId, subjectId, trialId) {
        try {
            const response = await fetch(`/apps/trial/subjects/${subjectId}/profiles?trial_id=${trialId}`);
            const result = await response.json();

            const historyContent = document.getElementById('profile-history-content');

            if (result.success) {
                if (result.profiles.length === 0) {
                    historyContent.innerHTML = '<div class="alert alert-info">暂无历史备注</div>';
                    return;
                }

                let html = '<div class="list-group">';
                result.profiles.forEach(profile => {
                    // 根据confidentiality字段获取对应的显示名称和样式
                    let secretLevelText = '普通档案';
                    let badgeClass = 'bg-secondary';

                    switch (profile.confidentiality) {
                        case 'TopSecret':
                            secretLevelText = '绝密档案';
                            badgeClass = 'bg-danger';
                            break;
                        case 'Secret':
                            secretLevelText = '机密档案';
                            badgeClass = 'bg-warning text-dark';
                            break;
                        case 'Confidential':
                            secretLevelText = '内部档案';
                            badgeClass = 'bg-info text-dark';
                            break;
                        case 'Unclassified':
                        default:
                            secretLevelText = '普通档案';
                            badgeClass = 'bg-secondary';
                            break;
                    }

                    let attachmentsHtml = '';
                    if (profile.attachment_urls) {
                        attachmentsHtml = '<div class="d-flex flex-wrap gap-2 mt-2">';
                        const urls = JSON.parse(profile.attachment_urls);
                        urls.forEach(url => {
                            attachmentsHtml += `<a href="javascript:showImagePreviewModal('${url}')" class="me-2">
                                <img src="${url}" alt="附件" class="img-thumbnail" style="width: 80px; height: 80px; object-fit: cover;">
                            </a>`;
                        });
                        attachmentsHtml += '</div>';
                    }

                    // 使用add_time字段，转换为可读的日期时间
                    const createdAt = new Date(profile.add_time * 1000).toLocaleString();

                    html += `
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <small class="text-muted">${createdAt} · ${profile.operator_name || '系统'} · <span class="badge ${badgeClass}">${secretLevelText}</span></small>
                        </div>
                        <p class="mb-1 mt-2">${profile.content}</p>
                        ${attachmentsHtml}
                    </div>`;
                });
                html += '</div>';

                historyContent.innerHTML = html;
            } else {
                historyContent.innerHTML = `<div class="alert alert-danger">${result.message || '加载备注历史失败'}</div>`;
            }
        } catch (error) {
            console.error('加载备注历史失败:', error);
            document.getElementById('profile-history-content').innerHTML = '<div class="alert alert-danger">加载备注历史失败，请重试</div>';
        }
    }

    // 提交备注档案
    async function submitProfile() {
        const form = document.getElementById('profileForm');
        const subjectId = document.getElementById('profile-subject-id').value;
        const trialId = document.getElementById('profile-trial-id').value;
        const userId = document.getElementById('profile-user-id').value;
        const content = form.querySelector('[name="content"]').value;
        const confidentiality = form.querySelector('[name="secretLevel"]').value;
        const attachmentUrls = document.getElementById('profile-attachment-urls').value;

        if (!content) {
            alert('请填写备注内容');
            return;
        }

        try {
            const response = await fetch(`/apps/trial/subjects/${subjectId}/profile`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    trialId,
                    userId,
                    content,
                    confidentiality,
                    attachmentUrls: attachmentUrls ? JSON.parse(attachmentUrls) : []
                })
            });

            const result = await response.json();

            if (result.success) {
                alert('备注档案保存成功');
                loadProfileHistory(userId, subjectId, trialId);
                form.reset();
                document.getElementById('upload-preview').innerHTML = '';
                document.getElementById('profile-attachment-urls').value = '';
            } else {
                alert(result.message || '保存备注档案失败');
            }
        } catch (error) {
            console.error('保存备注档案失败:', error);
            alert('保存备注档案失败，请重试');
        }
    }

    // 上传附件
    async function uploadAttachments() {
        const fileInput = document.getElementById('profile-file-upload');
        const files = fileInput.files;
        const uploadBtn = document.getElementById('upload-btn');

        if (!files || files.length === 0) {
            alert('请选择要上传的文件');
            return;
        }

        const uploadPreview = document.getElementById('upload-preview');
        const attachmentUrlsInput = document.getElementById('profile-attachment-urls');

        // 显示上传中状态
        uploadBtn.disabled = true;
        uploadBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 上传中...';

        try {
            const uploadPromises = [];
            const uploadedUrls = [];

            // 如果已有上传文件，获取现有URL
            let existingUrls = [];
            if (attachmentUrlsInput.value) {
                try {
                    existingUrls = JSON.parse(attachmentUrlsInput.value);
                } catch (e) {
                    existingUrls = [];
                }
            }

            // 上传每个文件
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const formData = new FormData();
                formData.append('file', file);

                const uploadPromise = fetch('https://mall.totembio.cn/api/uploadMtaFile', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(result => {
                    if (result.data && result.data.src) {
                        uploadedUrls.push(result.data.src);

                        // 创建预览
                        const previewItem = document.createElement('div');
                        previewItem.className = 'position-relative';
                        previewItem.innerHTML = `
                            <img src="${result.data.src}" class="img-thumbnail" style="width: 100px; height: 100px; object-fit: cover;">
                            <button type="button" class="btn-close position-absolute top-0 end-0 bg-danger" 
                                    style="font-size: 0.7rem;" data-url="${result.data.src}"></button>
                        `;

                        // 添加删除功能
                        const closeBtn = previewItem.querySelector('.btn-close');
                        closeBtn.addEventListener('click', function() {
                            const url = this.getAttribute('data-url');
                            removeAttachment(url);
                            previewItem.remove();
                        });

                        uploadPreview.appendChild(previewItem);
                        return result.data.src;
                    } else {
                        throw new Error(result.message || '上传失败');
                    }
                });

                uploadPromises.push(uploadPromise);
            }

            const results = await Promise.all(uploadPromises);

            // 合并新上传的URL和现有的URL
            const allUrls = [...existingUrls, ...uploadedUrls];

            // 更新隐藏字段
            attachmentUrlsInput.value = JSON.stringify(allUrls);

            // 重置文件输入
            fileInput.value = '';

        } catch (error) {
            console.error('上传文件失败:', error);
            alert('上传文件失败: ' + error.message);
        } finally {
            // 恢复上传按钮状态
            uploadBtn.disabled = false;
            uploadBtn.innerHTML = '上传';
        }
    }

    // 移除附件
    function removeAttachment(url) {
        const attachmentUrlsInput = document.getElementById('profile-attachment-urls');
        let urls = [];

        try {
            urls = JSON.parse(attachmentUrlsInput.value);
        } catch (e) {
            urls = [];
        }

        // 从URL数组中移除指定URL
        const updatedUrls = urls.filter(item => item !== url);

        // 更新隐藏字段
        attachmentUrlsInput.value = JSON.stringify(updatedUrls);
    }

    // 从URL创建预览图片
    function createPreviewsFromUrls(urls) {
        if (!urls || urls.length === 0) return;

        const uploadPreview = document.getElementById('upload-preview');
        uploadPreview.innerHTML = '';

        urls.forEach(url => {
            const previewItem = document.createElement('div');
            previewItem.className = 'position-relative';
            previewItem.innerHTML = `
                <img src="${url}" class="img-thumbnail" style="width: 100px; height: 100px; object-fit: cover;">
                <button type="button" class="btn-close position-absolute top-0 end-0 bg-danger" 
                        style="font-size: 0.7rem;" data-url="${url}"></button>
            `;

            // 添加删除功能
            const closeBtn = previewItem.querySelector('.btn-close');
            closeBtn.addEventListener('click', function() {
                const url = this.getAttribute('data-url');
                removeAttachment(url);
                previewItem.remove();
            });

            uploadPreview.appendChild(previewItem);
        });
    }

    // 页面加载完成后初始化上传功能
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化文件上传按钮
        const uploadBtn = document.getElementById('upload-btn');
        if (uploadBtn) {
            uploadBtn.addEventListener('click', uploadAttachments);
        }
    });

    // 显示图片弹窗
    function showImagePreviewModal(imgUrl) {
        // 创建模态框元素
        let modal = document.createElement('div');
        modal.className = 'modal fade';
        modal.id = 'imagePreviewModal';
        modal.setAttribute('tabindex', '-1');

        modal.innerHTML = `
            <div class="modal-dialog modal-dialog-centered modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">图片预览</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body text-center">
                        <img src="${imgUrl}" class="img-fluid" style="max-height: 70vh;">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        `;

        // 添加到页面
        document.body.appendChild(modal);

        // 显示模态框
        const modalInstance = new bootstrap.Modal(modal);
        modalInstance.show();

        // 模态框关闭后移除DOM元素
        modal.addEventListener('hidden.bs.modal', function() {
            document.body.removeChild(modal);
        });
    }
</script> 
